package be.groept.ace.enquete.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import be.groept.ace.enquete.model.beans.Question;
import be.groept.ace.enquete.model.beans.Survey;
import be.groept.ace.enquete.utils.BeanUtils;

/**
 * Servlet implementation class AdminQuestionServlet
 */
@WebServlet("/admin/question/*")
public class AdminQuestionServlet extends AdminServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(AdminQuestionServlet.class);

	@Override
	protected int handleGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		setQuestionFormAttributes(request, response);	
		return 200;
	}

	@Override
	protected int handlePost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		@SuppressWarnings("unchecked")
		List<String> errors = (List<String>) request.getAttribute("errors");
		Survey survey = (Survey) session.getAttribute("survey");
		logger.debug("hier gekomen - survey: aantal vragen = " + survey.getQuestionSet().size());
		for (Question q : survey.getQuestionSet()) {
			logger.debug(String.format("hier gekomen - question %s en hashcode: %d", q.toString(), q.hashCode()));
		}
		Question question = new Question();
		question.setSurvey(survey);
		BeanUtils.mapQuestionPostParameters(question, request.getParameterMap(), logger);
		if(!question.isValid(errors)) {
			request.setAttribute("question", question);
			setQuestionFormAttributes(request, response);
		} else {
			survey.addQuestion(question);
			logger.debug(String.format("hier gekomen - nieuwe question %s en hashcode: %d", question.toString(), question.hashCode()));
			for (Question q : survey.getQuestionSet()) {
				logger.debug(String.format("hier gekomen - question %s en hashcode: %d", q.toString(), q.hashCode()));
			}
			request.setAttribute("redirect", request.getContextPath() + "/admin/enquete");
			return 302;//redirect to questionpage
		}
		return 200;
	}

	private void setQuestionFormAttributes(HttpServletRequest request, HttpServletResponse response) {
		setForm(request, true);
		setFormActionUrl(request, response.encodeURL(request.getContextPath() + "/admin/question"));
		setPage(request, "questionForm");
		setTitle(request, "Nieuwe Vraag");
		setNavigationSelectedLink(request, 1);
		addHeaderLink(request, 1, "Bewaar", "save");
	}
}
